<template>
  <DeviceCard :title="title" :status="status" custom-class="pressure-card">
    <div class="pressure-value">
      {{ value }} <span>{{ unit }}</span>
    </div>
    <div class="last-update">
      最后更新: {{ lastUpdateTime }}
    </div>
  </DeviceCard>
</template>

<script>
import DeviceCard from './DeviceCard.vue';
import socketService from '../socket';

export default {
  name: 'BarometricPressureSensor',
  components: {
    DeviceCard
  },
  props: {
    deviceId: {
      type: String,
      required: true
    },
    title: {
      type: String,
      default: '大气压传感器'
    }
  },
  data() {
    return {
      value: "0",
      unit: 'hPa',
      status: 'normal',
      lastUpdateTime: ''
    };
  },
  methods: {
    formatTime(timestamp) {
      const date = new Date(timestamp);
      return date.toLocaleString();
    }
  },
  mounted() {
    // 请求初始数据
    socketService.requestInitialData((data) => {
      if (data.barometricPressure && data.barometricPressure.deviceId === this.deviceId) {
        this.value = data.barometricPressure.value;
        this.unit = data.barometricPressure.unit || 'hPa';
        this.status = data.barometricPressure.status || 'normal';
        this.lastUpdateTime = this.formatTime(Date.now());
      }
    });

    // 订阅大气压更新
    this.unsubscribe = socketService.subscribeToDeviceUpdates('barometric-pressure', (data) => {
      if (data.deviceId === this.deviceId) {
        this.value = data.value;
        this.unit = data.unit || 'hPa';
        this.status = data.status || 'normal';
        this.lastUpdateTime = this.formatTime(data.timestamp);
      }
    });
  },
  beforeDestroy() {
    if (this.unsubscribe) {
      this.unsubscribe();
    }
  }
};
</script>

<style scoped>
.pressure-card {
  border-left: 4px solid #4CAF50; /* 绿色边框，与温度传感器的蓝色区分 */
}
.pressure-value {
  font-size: 24px;
  font-weight: bold;
  margin: 15px 0;
}
.last-update {
  font-size: 12px;
  color: #666;
}
</style>